package cn.hn.comm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Element;

public class Tools {

	private static long randomseed = 0;
	
	/** 
     * 删除input字符串中的html格式 
     *  
     * @param input 
     * @param length 
     * @return 
     */  
    public static String splitAndFilterString(String input, int length) {  
        if (input == null || input.trim().equals("")) {  
            return "";  
        }  
        // 去掉所有html元素,  
        String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(  
                "<[^>]*>", "");  
        str = str.replaceAll("[(/>)<]", "");  
        int len = str.length();  
        if (len <= length) {  
            return str;  
        } else {  
            str = str.substring(0, length);  
            str += "......";  
        }  
        return str;  
    }  	
	
	/**
	 * 得到时间
	 * @param time
	 * @param format
	 * @return
	 * @throws ParseException
	 */
	public static Long getTime(String time,String format) throws ParseException
	{
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = sdf.parse(time);
		return date.getTime();
	}
	
	public static Date getDate(String timeZone,Long time) {
		
//		if(timeZone==null)
//		{
//			timeZone="GMT+8";
//		}
//		
//		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
//		calendar.setTimeInMillis(time);
//		Date d = calendar.getTime();
//		return d;
		return new Date(time);
	}	

	public static Date getCurDate(String timeZone) {
		
//		if(timeZone==null)
//		{
//			timeZone="GMT+8";
//		}
//		
//		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
//		Date d = calendar.getTime();
//		return d;
		return new Date();
	}

	public static String addHrefToKeyword(String html, String keyword,
			String href) {
		String backHtml = html;
		String ahref = "<a href=\"" + href + "\">" + keyword + "</a>";

		backHtml = backHtml.replace(keyword, ahref);

		return backHtml;
	}

	/**
	 * 全部替换超链接
	 * 
	 * @param html
	 *            原html
	 * @param href
	 *            超链
	 * @return
	 */
	public static String replaceAllHref(String html, String href) {
		String backHtml = html;
		String ahref = "\"" + href + "\"";

		// 要替换的关键字
		Map mapReplaceKeyWord = new HashMap<String, Object>();

		Pattern p = Pattern
				.compile("<a[^>]*href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))[^>]*>(.*?)</a>");
		Matcher m = p.matcher(html);
		while (m.find()) {
			mapReplaceKeyWord.put(m.group(1), "");
		}

		// 替换关键字
		String strKeyWord;
		if (mapReplaceKeyWord.size() > 0) {
			Set keyWord = mapReplaceKeyWord.keySet();
			Iterator iterKeyword = keyWord.iterator();
			while (iterKeyword.hasNext()) {
				strKeyWord = (String) iterKeyword.next();
				backHtml = backHtml.replace(strKeyWord, ahref);
			}
		}

		return backHtml;
	}

	/**
	 * 递归出所有符合条件的元素
	 * 
	 * @param fatherElement
	 * @param listElement
	 * @param key
	 * @return
	 */
	public List<Element> getElements(Element fatherElement,
			List<Element> listElement, String key) {
		Iterator<Element> itera = fatherElement.elementIterator();

		Element curElement;
		while (itera.hasNext()) {
			curElement = itera.next();
			if (curElement.getName().equals(key)) {
				listElement.add(curElement);
			}
			// 递归
			getElements(curElement, listElement, key);
		}

		return listElement;
	}

	/**
	 * 提取"<title>XXXX</title>"中的文字XXXX
	 * 
	 * @param html
	 *            要解析的html文档内容
	 * @return 解析结果，可以多次匹配，每次匹配的结果按文档中出现的先后顺序添加进结果List
	 */
	public static List getHtmlNodes(String html, String regex) {
		List resultList = new ArrayList();
		// Pattern p =
		// Pattern.compile("<title>([^</title>]*)");//匹配<title>开头，</title>结尾的文档
		Pattern p = Pattern.compile(regex, Pattern.DOTALL);
		Matcher m = p.matcher(html);// 开始编译
		while (m.find()) {
			resultList.add(m.group(1));// 获取被匹配的部分
		}
		return resultList;
	}

	public static Object getObjectInstace(String classPath) {
		Class c;
		try {
			c = Class.forName(classPath);
			Object obj = c.newInstance();
			return obj;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static int getRandomInt(int min, int max) {
		randomseed++;
		int iBack = min;
		Random random = new Random(randomseed);
		iBack += random.nextInt(max - min);
		return iBack;
	}

	/**
	 * 得到规定字符集的字符串
	 * 
	 * @param str
	 * @param orgCharset
	 * @param targetCharset
	 * @return
	 */
	public static String getCharsetString(String str, String orgCharset,
			String targetCharset) {
		try {
			if (orgCharset != null) {
				return new String(str.getBytes(orgCharset), targetCharset);
			} else {
				return new String(str.getBytes(), targetCharset);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String args[]) {
		
		String str="你好，小三。撒地方水电费";
		str=addHrefToKeyword(str,"小三","http://www.tianxin007.com");
		System.out.println(str);
		
//		String html = " <a href=\"http://www.sina.com\"> 原创 </a>小三地带";
//		String str = " <html> <body> <a   href=\"index.html\"> 首页 </a> <br> 小三地带 <a   href=\"last.html\"> 未页 </a> ";
//		str = str + " <p> asf我是小三asfs </p> ";
//		str = str + " <a   href=\"first.html\"> 第一页 </a> </body> </html> ";		
//		
//		
//		str=replaceAllHref(str,"http://www.tianxin007.com");
//		
//		System.out.println(str);
		
//		for (int i = 0; i < 10; i++)
//			System.out.println(getRandomInt(1, 10));

		// String html =
		// "<title>ABCD</title>gsdggas<title></title>jkll<title>005</title>";
		// // 简单示例，相当于String html=getHtml(String urlString);
		// List resultList = getHtmlNodes(html, "<title>([^</title>]*)");
		// for (Iterator iterator = resultList.iterator(); iterator.hasNext();)
		// {
		// String context = (String) iterator.next();
		// System.out.println(context);
		// }
	}

}
